package com.badger.spring.boot.security.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.badger.spring.boot.security.entity.SystemUserDetails;
import com.badger.spring.boot.security.entity.UserEntity;
import com.badger.spring.boot.security.sms.SmsAuthenticationProvider;

@Configuration
public class SecurityConfig {

    static final List<UserEntity> USER_LIST = new ArrayList<>();

    static {
        for (int i = 1; i < 6; i++) {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(i);
            userEntity.setName("测试人员" + i);
            userEntity.setUsername("ceshi_" + i);
            // 密码使用 PasswordEncoder 类对123456 加密之后的结果
            userEntity.setPassword("$2a$10$D1q09WtH./yTfFTh35n0k.o6yZIXwxIW1/ex6/EjYTF7EiNxXyF7m");
            userEntity.setEmail("100" + i + "@qq.com");
            userEntity.setPhone("186xxxx351" + i);
            USER_LIST.add(userEntity);
        }
    }

    /************************帐号密码登录**********************/
    @Bean
    public UserDetailsService usernamePasswordUserDetails() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                UserEntity user = null;
                for (UserEntity userEntity : USER_LIST) {
                    if (username.equals(userEntity.getUsername()) || username.equals(userEntity.getPhone())
                            || username.equals(userEntity.getEmail())) {
                        user = userEntity;
                    }
                }
                if (user != null) {
                    return new SystemUserDetails(user.getUsername(), user.getPassword(), user, null);
                }
                throw new UsernameNotFoundException("用户未注册，请先注册");
            }
        };
    }

    @Bean
    public AuthenticationProvider usernamePasswordAuthenticationProvider() {
        return new UsernamePasswordAuthenticationProvider(usernamePasswordUserDetails());
    }

    /************************手机+短信登录**********************/
    @Bean
    public AuthenticationProvider phoneSmsAuthenticationProvider() {
        return new SmsAuthenticationProvider(usernamePasswordUserDetails());
    }
}
